package com.blb.zycommunity.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ExcelDownloadUtil {
    /**
     * @param response
     * @param filename  excel文件名
     * @param dataClass 被导出类模板
     * @param datalist  被导出的数据集合
     * @throws IOException
     */
    public static <T> void excelDownload(HttpServletResponse response, String filename, Class dataClass, List<T> datalist) throws IOException {
        try {
            //            xlsx类型的文件
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //xls类型的文件
            //            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
            //            告诉浏览器下载
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            System.out.println(dataClass.getClass());
            //        EasyExcel.write(response.getOutputStream(), dataClass.getClass()).sheet(filename).doWrite(datalist);
            ServletOutputStream outputStream = response.getOutputStream();
            if (outputStream != null) {
                EasyExcel.write(outputStream, dataClass).registerConverter(new LongStringConverter()).sheet(filename).doWrite(datalist);
            } else {
                throw new Exception("无法获取响应输出流");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 将传入的json格式的string类型数组转换为空类型的集合
     *
     * @param ids
     * @return
     */
    public static ArrayList<Long> toList(String ids) {
        String[] array = JSON.parseArray(ids).toArray(new String[0]);
        ArrayList<Long> idsLong = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            idsLong.add(Long.parseLong(array[i]));
        }
        return idsLong;
    }
}
